<template>
  <div class="userInterface">
    <div class="top">
      <div class="avatar-and-buttons">
        <el-image :src="baseUrl + userInfo.avatarUrl" />
        <div class="button-group">
          <template v-if="userFocusInfoMap[userInfo.user.id]">
            <el-button
              v-if=" userFocusInfoMap[userInfo.user.id].isFocus === 0 || userFocusInfoMap[userInfo.user.id].isFocus === undefined"
              type="primary"
              plain
              size="mini"
              icon="el-icon-plus"
              @click="handleFocus(userInfo, userFocusInfoMap[userInfo.user.id] ? userFocusInfoMap[userInfo.user.id].isFocus : undefined)"
            >关注</el-button>
            <el-button
              v-else
              type="info"
              plain
              size="mini"
              icon="el-icon-check"
              @click="handleFocus(userInfo, userFocusInfoMap[userInfo.user.id] ? userFocusInfoMap[userInfo.user.id].isFocus : undefined)"
            >已关注</el-button>
          </template>
          <el-button
            v-if="parseInt(userId) === parseInt(acceptUserId)"
            type="primary"
            plain
            size="mini"
            @click="goUserInfo"
          >编辑资料</el-button>
        </div>
      </div>
      <div class="userInfo">
        <h3>{{ userInfo.nickName }}</h3>
        <p>性别：{{ userInfo.gender === 0 ? '男' : '女' }}</p>
        <p>邮箱：{{ userInfo.email ? userInfo.email : '暂无' }}</p>
        <p>手机号：{{ userInfo.phone ? userInfo.phone : '暂无' }}</p>
        <p>个人简介：{{ userInfo.introduction ? userInfo.introduction : '暂无' }}</p>
      </div>
    </div>

    <el-tabs v-model="tabName" type="border-card" @tab-click="handleTabClick">
      <el-tab-pane :lazy="true" label="发帖" name="发帖">
        <el-empty v-if="postList.length === 0" description="暂无相关帖子" />
        <post
          v-for="item in postList"
          v-else
          :key="item.id"
          class="post"
          :post-info="item"
          :like="handleLike"
          :dislike="handleDislike"
          :collect="handleCollect"
          :report="handleReport"
          @click.native="goPostDetail(item)"
        />
      </el-tab-pane>
      <el-tab-pane :lazy="true" label="收藏" name="收藏">
        <el-empty v-if="postList.length === 0" description="暂无相关帖子" />
        <post
          v-for="item in postList"
          v-else
          :key="item.id"
          class="post"
          :post-info="item"
          :like="handleLike"
          :dislike="handleDislike"
          :collect="handleCollect"
          :report="handleReport"
          @click.native="goPostDetail(item)"
        />
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import post from '@/components/post'
import { savePostFeedback, updatePostFeedback } from '@/api/postfeedback'
import { getUserInfoVoList } from '@/api/userInfo'
import { mapGetters } from 'vuex'
import { saveUserFocusInfo, updateUserFocusInfo, getUserFocusInfoList } from '@/api/userFocusInfo'
import { formatDateTime } from '@/utils/dateUtil'
import { getPostVoList } from '@/api/post'
import pubsub from 'pubsub-js'

export default {
  name: 'UserInterface',
  components: {
    post
  },
  data() {
    return {
      baseUrl: process.env.VUE_APP_BASE_API,
      acceptUserId: parseInt(this.$route.query.userId),
      userInfo: {
        user: {}
      },
      tabName: '发帖',
      userFocusInfoMap: {},
      postList: [],
      pageNum: 1,
      pageSize: 5,
      pubsubId: undefined,
      focusUserList: undefined,
      isCollect: false
    }
  },
  computed: {
    ...mapGetters(['userId'])
  },
  watch: {
    $route() {
      location.reload()
    }
  },
  beforeMount() {
    this.getUserInfo()
    this.getPostVoList()
    this.subscribeUpdatePostVoList()
  },
  beforeDestroy() {
    pubsub.unsubscribe(this.pubsubId)
  },
  methods: {
    subscribeUpdatePostVoList() {
      this.pubsubId = pubsub.subscribe('updateData', () => {
        this.pageSize += 5
        this.getPostVoList()
      })
    },
    async getPostVoList() {
      const userIds = this.focusUserList?.reduce((cur, value) => {
        return [...cur, value.isFocus === 1 ? value.beFocusedUserId : '']
      }, [])
      if (userIds?.length === 0) userIds.push(-1)
      const searchParam = {
        pageNum: this.pageNum,
        pageSize: this.pageSize,
        searches: [
          {
            key: 'post.status',
            rule: '=',
            value: 1
          },
          {
            key: 'post.user_id',
            rule: '=',
            value: this.acceptUserId
          }
        ]
      }
      if (this.isCollect) {
        searchParam.searches.push(
          {
            key: 'is_collect',
            rule: '=',
            value: 0
          }
        )
      }
      const { data } = await getPostVoList(searchParam)
      this.postList = data.list
    },
    async handleLike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleDislike(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isLike: 1
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    async handleCollect(postInfo) {
      const postfeedback = {
        postId: postInfo.id,
        isCollect: postInfo.isCollect === 0 ? 1 : 0
      }
      if (postInfo.isLike === null && postInfo.isCollect === null) {
        await savePostFeedback(postfeedback)
        this.getPostVoList()
      } else {
        await updatePostFeedback(postfeedback)
        this.getPostVoList()
      }
    },
    handleReport(postInfo) {
      this.$router.push({
        path: '/report',
        query: {
          postId: postInfo.id
        }
      })
    },
    goPostDetail(item) {
      this.$router.push({
        path: '/postDetail',
        query: {
          postId: item.id
        }
      })
    },
    async handleFocus(userInfo, isFocus) {
      try {
        if (isFocus !== undefined) {
          await updateUserFocusInfo({
            beFocusedUserId: userInfo.id,
            isFocus: isFocus === 0 ? 1 : 0,
            focusDate: formatDateTime(new Date())
          })
        } else {
          await saveUserFocusInfo({
            beFocusedUserId: userInfo.id,
            isFocus: 1,
            focusDate: formatDateTime(new Date())
          })
        }
      } catch (error) {
        console.log(error)
      }
      this.getUserFocusInfoList()
    },
    getUserFocusInfoList() {
      getUserFocusInfoList().then(res => {
        const userFocusInfoList = res.data
        this.userFocusInfoMap = userFocusInfoList?.reduce((cur, value) => {
          cur[value.beFocusedUserId] = value
          return cur
        }, {})
        this.userFocusInfoMap = this.userFocusInfoMap ? this.userFocusInfoMap : {}
      }, err => {
        console.log(err)
      })
    },
    goUserInfo() {
      this.$router.push({
        path: '/userInfo'
      })
    },
    handleTabClick(tab) {
      switch (tab.name) {
        case '发帖':
          this.isCollect = false
          this.getPostVoList()
          break
        case '回答':
          console.log('回答')
          break
        case '关注':
          console.log('关注')
          break
        case '收藏':
          this.isCollect = true
          this.getPostVoList()
          break
        default:
          break
      }
    },
    async getUserInfo() {
      const searchParams = {
        pageNum: 1,
        pageSize: 5,
        searches: [
          {
            key: 'user_id',
            rule: '=',
            value: this.acceptUserId
          }
        ]
      }
      const { data } = await getUserInfoVoList(searchParams)
      this.getUserFocusInfoList()
      this.userInfo = data.list[0]
    }
  }
}
</script>

<style lang="scss" scoped>
.userInterface {
  background-color: #fff;
  width: 80%;
  margin: 20px auto;
  padding: 20px;
  border-radius: 20px;
  box-shadow: 0 0 10px black;
  .top {
    display: flex;
    .avatar-and-buttons {
      .el-image {
        width: 160px;
        height: 160px;
        border-radius: 20%;
        display: block;
        margin-right: 10px;
      }
      .button-group {
        text-align: center;
        margin: 10px 0;
      }
    }
    .userInfo {
      flex-grow: 1;
      border: 1px solid rgb(219, 219, 219);
      border-radius: 10px;
      background: #f6f6f6;
      padding: 10px;
      align-self: flex-start;
      margin-top: 10px;
      h3,p {
        margin: 0;
      }
      p {
        margin-top: 10px;
      }
    }
  }
  .el-tabs {
    .post {
      margin: 10px auto;
      width: 100%;
      &:hover {
        cursor: pointer;
        outline: 3px solid rgb(36, 36, 36);
      }
    }
  }
}
</style>
